package org.spider.spiderweb.websocket;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.context.SpiderContext;
import org.spider.api.domain.utilDomain.SpiderLog;
import org.spider.api.domain.utilDomain.SpiderOutput;

import javax.websocket.Session;
import java.util.Date;

/**
 * 保存Socket上下文中常用的变量<br>
 * 可以利用
 */
public class WebSocketContext extends SpiderContext {
    private Session session;
    private Logger logger= LoggerFactory.getLogger(WebSocketContext.class);
    public WebSocketContext(Session session){
        this.session=session;
        logger.info("当前websocket context id为:{}",super.getId());
    }


    public void addOutput(SpiderOutput output){
        this.write(WebSocketEvent.output(output));
    }

    public void log(SpiderLog log){
        this.write(WebSocketEvent.log(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"),log));
    }
    public void write(WebSocketEvent event){
        try {
            String message = JSON.toJSONString(event);
            if (session.isOpen()) {
                synchronized (session) {
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (Exception e){
        }
    }
}
